package design.graduation.novelsystem.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: 洪少尉
 * @Date: 2020/4/17 22:47
 * @Description: http请求工具
 */
public class HttpClientUtils {
	/**
	 * 连接池管理器
	 */
	private final PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
	/**
	 * 构造函数
	 * 配置连接池管理器
	 */
	public HttpClientUtils(){
		this.poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
		//设置最大连接数
		this.poolingHttpClientConnectionManager.setMaxTotal(100);
		//设置每个主机（host）的最大连接数
		this.poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10);
	}

	/**
	 * 文件下载
	 * @param url 文件下载路径
	 * @param localSaveAddr 下载保存路径
	 * @param fileName	下载文件重命名
	 */
	public static boolean download(String url,String localSaveAddr,String fileName){
		CloseableHttpClient httpClient = HttpClients.custom()
				//通过连接池创建
				.setConnectionManager(new HttpClientUtils().poolingHttpClientConnectionManager)
				.build();
		//创建httpGet请求对象，设置url
		HttpGet httpGet = new HttpGet(url);

		httpGet.setConfig(new HttpClientUtils().getConfig());
		CloseableHttpResponse response = null;
		boolean flag = false;
		try {
			//使用HttpClient发起请求，获取响应
			response = httpClient.execute(httpGet);
			/*
				解析响应，返回结果
				响应状态值为200则表示成功
			 */
			if(response.getStatusLine().getStatusCode() == 200){
				//判断响应体是否为空
				if(response.getEntity() != null){
					//System.out.println("开始下载"+fileName);
					//下载文件
					response.getEntity().writeTo(new FileOutputStream(localSaveAddr+fileName));
					flag = true;
				}
			}
		}catch (Exception e){
			System.out.println("请求失败");
		}finally {
			if(response != null){
				try {
					//关闭流
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
	/**
	 * 请求参数设置
	 * @return	请求参数
	 */
	public RequestConfig getConfig(){
		// HttpHost proxy =new HttpHost("117.90.3.241",9999);
		RequestConfig config = RequestConfig.custom()
				//创建连接的最长时间
				.setConnectTimeout(1000)
				//获取连接的最长时间
				.setConnectionRequestTimeout(500)
				//数据传输的最长时间
				.setSocketTimeout(10*1000)
				//设置代理
				// .setProxy(proxy)
				.build();
		return config;
	}
}
